package io.renren.modules.sys.controller;


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import io.renren.common.validator.ValidatorUtils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.CustomerEntity;
import io.renren.modules.sys.entity.CustomerEntity2;
import io.renren.modules.sys.entity.CustomerLogEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.CustomerLogService;
import io.renren.modules.sys.service.CustomerService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 客户表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-12-13 21:29:25
 */
@RestController
@RequestMapping("sys/customer")
public class CustomerController extends AbstractController  {
    @Autowired
    private CustomerService customerService;
    
    @Autowired
    private SysUserDao sysUserDao;
    
    @Autowired
    private CustomerLogService customerLogService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
    	SysUserEntity sysUserEntity=getUser();
    	Integer customerStatus=null;
    	if(null!=params.get("customerStatus")) {
    		customerStatus=Integer.valueOf(params.get("customerStatus").toString());
    		if(customerStatus==0) {
    			params.put("userId", sysUserEntity.getUserId());
    		}
    	}
        PageUtils page = customerService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
        CustomerEntity customer = customerService.selectById(id);

        return R.ok().put("customer", customer);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody CustomerEntity customer){
    	Map<String, Object> params=new HashMap<>();
		params.put("name", customer.getName());
		if(customerService.queryPage(params).getList().size()>0){
			return R.error("用户已存在");
		}
    	SysUserEntity sysUserEntity=getUser();
    	Map<String, Object> params2=new HashMap<>();
    	params2.put("userId", sysUserEntity.getUserId());
        PageUtils page = customerService.queryPage(params2);
    	customer.setUserId(sysUserEntity.getUserId().intValue());
    	customer.setUserName(sysUserEntity.getUsername());
    	customer.setAddDate(new Date());
    	customer.setUpdDate(new Date());
        if(page.getTotalCount()>=sysUserEntity.getNum2()) {
        	customer.setUserId(0);
        	customer.setUserName("公告会员");
        	customer.setCustomerStatus(2);
        }
        customerService.insert(customer);
        return R.ok();
    }
    
    /**
     * 修改
     */
    @RequestMapping("/update2")
    public R update2(@RequestBody CustomerEntity customer){
    	customer=customerService.selectById(customer.getId());
        ValidatorUtils.validateEntity(customer);
        SysUserEntity sysUserEntity=getUser();
    	customer.setUserId(sysUserEntity.getUserId().intValue());
    	customer.setUserName(sysUserEntity.getUsername());
    	customer.setCustomerStatus(0);
    	customer.setUpdDate(new Date());
        customerService.updateAllColumnById(customer);//全部更新
        CustomerLogEntity customerLog=new CustomerLogEntity();
    	customerLog.setAddDate(new Date());
    	customerLog.setUserId(sysUserEntity.getUserId().intValue());
    	customerLog.setUserName(sysUserEntity.getUsername());
    	customerLog.setCustomerId(customer.getId());
    	customerLog.setContent(sysUserEntity.getName()+"：采单了");
        customerLogService.insert(customerLog);
        return R.ok();
    }
    
    /**
     * 修改
     */
    @RequestMapping("/update3")
    public R update3(@RequestBody CustomerEntity customer){
        SysUserEntity sysUserEntity=getUser();
        ValidatorUtils.validateEntity(customer);
        customer=customerService.selectById(customer.getId());
    	customer.setUserId(0);
    	customer.setUserName("公告会员");
    	customer.setCustomerStatus(2);
    	customer.setUpdDate(new Date());
        customerService.updateAllColumnById(customer);//全部更新
        CustomerLogEntity customerLog=new CustomerLogEntity();
    	customerLog.setAddDate(new Date());
    	customerLog.setUserId(sysUserEntity.getUserId().intValue());
    	customerLog.setUserName(sysUserEntity.getUsername());
    	customerLog.setCustomerId(customer.getId());
    	customerLog.setContent(sysUserEntity.getName()+"更新到公共库");
        customerLogService.insert(customerLog);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody CustomerEntity customer){
        ValidatorUtils.validateEntity(customer);
        customer.setUpdDate(new Date());
        customerService.updateAllColumnById(customer);//全部更新
        CustomerLogEntity customerLog=new CustomerLogEntity();
        SysUserEntity sysUserEntity=getUser();
    	customerLog.setAddDate(new Date());
    	customerLog.setUserId(sysUserEntity.getUserId().intValue());
    	customerLog.setUserName(sysUserEntity.getUsername());
    	customerLog.setCustomerId(customer.getId());
    	customerLog.setContent(sysUserEntity.getName()+"更新资料");
        customerLogService.insert(customerLog);
        return R.ok();
    }
    
    /**
     * 修改
     */
    @RequestMapping("/update1")
    public R update1(@RequestBody CustomerEntity customer){
        ValidatorUtils.validateEntity(customer);
        customer.setUpdDate(new Date());
        customerService.updateAllColumnById(customer);//全部更新
        CustomerLogEntity customerLog=new CustomerLogEntity();
        SysUserEntity sysUserEntity=getUser();
    	customerLog.setAddDate(new Date());
    	customerLog.setUserId(sysUserEntity.getUserId().intValue());
    	customerLog.setUserName(sysUserEntity.getUsername());
    	customerLog.setCustomerId(customer.getId());
    	customerLog.setContent(sysUserEntity.getName()+"更新资料");
        customerLogService.insert(customerLog);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
        customerService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }
    
    /**
     * 删除
     */
    @RequestMapping("/isDelete")
    public R isDelete(@RequestBody CustomerEntity customer){
    	CustomerEntity customer2=customerService.selectById(customer.getId());
    	customer2.setReason(customer.getReason());
    	customer2.setStatus(0);
    	customer2.setUpdDate(new Date());
        customerService.updateAllColumnById(customer2);//全部更新
        CustomerLogEntity customerLog=new CustomerLogEntity();
        SysUserEntity sysUserEntity=getUser();
    	customerLog.setAddDate(new Date());
    	customerLog.setUserId(sysUserEntity.getUserId().intValue());
    	customerLog.setUserName(sysUserEntity.getUsername());
    	customerLog.setCustomerId(customer.getId());
    	customerLog.setContent(sysUserEntity.getName()+"放入待删除");
        customerLogService.insert(customerLog);
        return R.ok();
    }
    
    /**
     * 列表
     */
    @RequestMapping("/dellist")
    public R dellist(@RequestParam Map<String, Object> params){
    	SysUserEntity sysUserEntity=getUser();
    	Integer customerStatus=null;
    	if(null!=params.get("customerStatus")) {
    		customerStatus=Integer.valueOf(params.get("customerStatus").toString());
    		if(customerStatus==0) {
    			params.put("userId", sysUserEntity.getUserId());
    		}
    	}
        PageUtils page = customerService.dellist(params);
        return R.ok().put("page", page);
    }
    
    
    /**
     * 申请待审核客户
     */
    @RequestMapping("/isMake")
    public R isMake(@RequestBody CustomerEntity customer){
    	CustomerEntity customer2=customerService.selectById(customer.getId());
    	customer2.setIsMake(1);
    	customer2.setUpdDate(new Date());
        customerService.updateAllColumnById(customer2);//全部更新
        CustomerLogEntity customerLog=new CustomerLogEntity();
        SysUserEntity sysUserEntity=getUser();
    	customerLog.setAddDate(new Date());
    	customerLog.setUserId(sysUserEntity.getUserId().intValue());
    	customerLog.setUserName(sysUserEntity.getUsername());
    	customerLog.setCustomerId(customer.getId());
    	customerLog.setContent(sysUserEntity.getName()+"申请审核客户");
        customerLogService.insert(customerLog);
        return R.ok();
    }
    
    /**
     * 列表
     */
    @RequestMapping("/makeList")
    public R makeList(@RequestParam Map<String, Object> params){
    	params.put("isMake", 1);
        PageUtils page = customerService.queryPage(params);
        return R.ok().put("page", page);
    }
    
    /**
     * 列表
     */
    @RequestMapping("/makeList2")
    public R makeList2(@RequestParam Map<String, Object> params){
    	params.put("isMake", 2);
        PageUtils page = customerService.queryPage(params);
        return R.ok().put("page", page);
    }
    
    
    /**
     * 更改已成交客户
     */
    @RequestMapping("/isMake2")
    public R isMake2(@RequestBody CustomerEntity customer){
    	CustomerEntity customer2=customerService.selectById(customer.getId());
    	customer2.setIsMake(2);
    	customer2.setUpdDate(new Date());
        customerService.updateAllColumnById(customer2);//全部更新
        CustomerLogEntity customerLog=new CustomerLogEntity();
        SysUserEntity sysUserEntity=getUser();
    	customerLog.setAddDate(new Date());
    	customerLog.setUserId(sysUserEntity.getUserId().intValue());
    	customerLog.setUserName(sysUserEntity.getUsername());
    	customerLog.setCustomerId(customer.getId());
    	customerLog.setContent(sysUserEntity.getName()+"更改为已成交客户");
        customerLogService.insert(customerLog);
        return R.ok();
    }
    
    /**
     * 批量更新跟进人
     * @param customerEntity2
     * @return
     */
    @RequestMapping("/updUserId")
    public R updAll(@RequestBody CustomerEntity2 customerEntity2) {
    	SysUserEntity sysUserEntity=sysUserDao.selectById(customerEntity2.getUserId());
    	for (int i = 0; i < customerEntity2.getIds().length; i++) {
    		CustomerEntity customer2=customerService.selectById(customerEntity2.getIds()[i]);
        	customer2.setUserId(sysUserEntity.getUserId().intValue());
        	customer2.setUserName(sysUserEntity.getUsername());
        	customer2.setUpdDate(new Date());
            customerService.updateAllColumnById(customer2);//全部更新
		}
    	return R.ok();
    }
    
    
    @RequestMapping("/excel")
    public R StorageImport(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws IOException {
		// 获取文件名
		String fileName = file.getOriginalFilename();
		java.util.List<CustomerEntity> customerEntityList=new ArrayList<>();

		// 初始化输入流
		if (true) {
			InputStream is = null;
			try {
				// 将上传的文件写入新建的文件中
				// file.transferTo(tempFile);
				// 根据新建的文件实例化输入流
				is = file.getInputStream();
				// 根据版本选择创建Workbook的方式
				Workbook wb = null;
				// 根据文件名判断文件是2003版本还是2007版本
				if (ExcelImportUtil.isExcel2007(fileName)) {
					wb = new XSSFWorkbook(is);
				} else {
					wb = new HSSFWorkbook(is);
				}
				// 读取exec内容
				Sheet sheet = wb.getSheetAt(0);
				SysUserEntity sysUserEntity=getUser();
				for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
					Row row = sheet.getRow(i);
if(null==row) {
	continue;
}
					Object name= row.getCell(0);
					Object industry= row.getCell(1);
					Object phone= row.getCell(2);
					Object contact= row.getCell(3);
					Object address= row.getCell(4);
					Object tel= row.getCell(5);
					Object url= row.getCell(6);
					Object businessLicense= row.getCell(7);
					Object companyProfile= row.getCell(8);
					Object capital= row.getCell(9);
					Object postalCode= row.getCell(10);
					Object remark= row.getCell(11);
					Object mobile= row.getCell(12);
					Object email= row.getCell(13);
					Object city= row.getCell(14);
					Object type= row.getCell(15);
					CustomerEntity customerEntity=new CustomerEntity();
					customerEntity.setName(name==null?null:name.toString());
					customerEntity.setIndustry(industry==null?null:industry.toString());
					customerEntity.setPhone(phone==null?null:phone.toString());
					customerEntity.setContact(contact==null?null:contact.toString());
					customerEntity.setAddress(address==null?null:address.toString());
					customerEntity.setTel(tel==null?null:tel.toString());
					customerEntity.setUrl(url==null?null:url.toString());
					customerEntity.setBusinessLicense(businessLicense==null?null:businessLicense.toString());
					customerEntity.setCompanyProfile(companyProfile==null?null:companyProfile.toString());
					customerEntity.setRemark(remark==null?null:remark.toString());
					customerEntity.setCapital(capital==null?null:capital.toString());
					customerEntity.setPostalCode(postalCode==null?null:postalCode.toString());
					customerEntity.setMobile(mobile==null?null:mobile.toString());
					customerEntity.setEmail(email==null?null:email.toString());
					customerEntity.setCity(city==null?null:city.toString());
					customerEntity.setUserId(sysUserEntity.getUserId().intValue());
					customerEntity.setUserName(sysUserEntity.getUsername());
					customerEntity.setAddDate(new Date());
					customerEntity.setUpdDate(new Date());
					customerEntity.setType(type==null?null:Integer.valueOf(type.toString()));
					customerEntityList.add(customerEntity);
					//customerService.insert(customerEntity);
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						is = null;
						e.printStackTrace();
					}
				}
			}
		}
		System.err.println(customerEntityList.size());
		return R.ok();
	}


}
